# -*- coding: utf-8 -*-
'''
生成二维码
'''
import os

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont 
import qrcode


QR_FLODER = 'qr_codes'

def generate_qrcode(idx):
    qr = qrcode.QRCode(
        version=3,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=8,
        border=1,
    )
    # 序号
    qr.add_data('http://customer.scaotu.cn/?desk={0}'.format(idx))
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    # PIL modes: https://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#modes
    # print(qr.print_tty())
    print(img.pixel_size)
    # img.show()

    # 背景
    qr_size = img.pixel_size
    bg_size = (qr_size, qr_size + 20)
    bg_img = Image.new('L', bg_size, 'white').convert('1')
    # 合并
    merge_size = (0, 0, qr_size, qr_size)
    bg_img.paste(img, merge_size)
    # 清理资源
    img.close()
    qr.clear()
    del img
    del qr
    # 序号文字
    txt = 'NO.{s:{c}>{n}}'.format(s=idx, n=6, c='0')
    # 绘制文字
    draw = ImageDraw.Draw(bg_img)
    fnt_size = 16
    fnt_file = r'msyh.ttf'
    fnt = ImageFont.truetype(fnt_file, fnt_size)
    txt_width, txt_height = draw.textsize(txt, font=fnt)
    print(txt_width, txt_height)
    txt_pos = (
        qr_size - txt_width - txt_height / 2,
        qr_size - txt_height / 4
    )
    draw.text(txt_pos, txt, font=fnt, fill='black')
    del draw
    # bg_img.show()
    file_name = '{0}.jpg'.format(txt[3:])
    save_path = os.path.join(QR_FLODER, file_name)
    bg_img.save(save_path)
    del bg_img

if __name__ == '__main__':
    if not os.path.exists(QR_FLODER):
        os.makedirs(QR_FLODER)
    for i in range(1, 1001):
        generate_qrcode(i)